﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.Remoting.Messaging;
using BCMS.Business.DataContract;
using Microsoft.Office.Interop.Excel;
using BCMS.Settings;
using BCMS.Business.Implementation;
using System.Diagnostics;

namespace BCMS.Forms.Functions
{
    public partial class frmImportClaimedCoupon : Form
    {
        public frmImportClaimedCoupon()
        {
            InitializeComponent();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        delegate List<CouponInfo> importReleaseDelegate(string fileName);
        delegate void updateCouponDelegate(List<CouponInfo> src);

        private void btnRun_Click(object sender, EventArgs e)
        {
            importReleaseDelegate import = new importReleaseDelegate(importData);
            import.BeginInvoke(txtFile.Text, callBack, null);
            lblStatus.Text = "Đang đọc tệp dữ liệu ...";
        }

        private void btnFileSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "File dữ liệu(*.xls)|*.xls";
            dialog.InitialDirectory = System.Windows.Forms.Application.StartupPath;
            dialog.Title = "CHỌN FILE NGUỒN";
            if (dialog.ShowDialog() == DialogResult.OK)
                txtFile.Text = dialog.FileName;
            lblStatus.Text = "Nhập thông tin về file dữ liệu.";
        }

        void callBack(IAsyncResult ar)
        {
            AsyncResult result = (AsyncResult)ar;
            // grab the delegate
            importReleaseDelegate del = (importReleaseDelegate)result.AsyncDelegate;
            List<CouponInfo> list = del.EndInvoke(ar);

            MethodInvoker updateUI = delegate
            {
                lblStatus.Text = "Đang cập nhật dữ liệu ...";
            };
            if (this.InvokeRequired)
            {
                this.Invoke(updateUI);
            }
            else
                updateUI();

            updateCoupon(list);
        }

        private void updateCoupon(List<CouponInfo> src)
        {
            try
            {
                DALclient client = new DALclient();
                client.ImportClaimCoupons(src);
                GlobalVars.ShowInfo("Cập nhật đữ liệu tự động [THÀNH CÔNG]");
            }
            catch (Exception ex)
            {
                GlobalVars.ShowError(ex.Message);

                MethodInvoker updateUI = delegate
                {
                    lblStatus.Text = "Quá trình cập nhật có [LỖI]";
                };
                if (this.InvokeRequired)
                {
                    this.Invoke(updateUI);
                }
                else
                    updateUI();
            }
        }

        private List<CouponInfo> importData(string sourceFile)
        {
            try
            {
                object sender = System.Threading.Thread.CurrentThread;
                ((System.Threading.Thread)sender).CurrentCulture = new System.Globalization.CultureInfo("en-US");
                List<CouponInfo> list = new List<CouponInfo>();
                ApplicationClass app = new ApplicationClass();
                Workbook book = null;
                Worksheet sheet = null;
                Range range = null;
                int[] Columns = { 1, 2, 3, 4, 5 };


                app.Visible = false;
                app.ScreenUpdating = false;
                app.DisplayAlerts = false;

                book = app.Workbooks.Open(sourceFile, Type.Missing, Type.Missing,
                    Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing
                     , Type.Missing, Type.Missing, Type.Missing, Type.Missing
                    , Type.Missing, Type.Missing, Type.Missing);
                sheet = (Worksheet)book.Worksheets[1];

                // get a range to work with
                range = sheet.get_Range("A1", Type.Missing);
                // get the end of values to the right (will stop at the first empty cell)
                range = range.get_End(XlDirection.xlToRight);
                // get the end of values toward the bottom, looking in the last column (will stop at first empty cell)
                range = range.get_End(XlDirection.xlDown);

                // get the address of the bottom, right cell
                string downAddress = range.get_Address(
                    false, false, XlReferenceStyle.xlA1,
                    Type.Missing, Type.Missing);

                // Get the range, then values from a1
                range = sheet.get_Range("A1", downAddress);
                object[,] values = (object[,])range.Value2;
                int totalRecord = values.GetLength(0);
                for (int i = 1; i < totalRecord; i++)
                {
                    CouponInfo item = new CouponInfo();
                    string sr = values[i, 1].ToString();
                    item.Serial = sr.Substring(0, 1) + '-' + sr.Substring(1, sr.Length-1);
                    item.ClaimDate = DateTime.FromOADate(Convert.ToDouble(values[i, 2]));
                    item.ClaimBy = GlobalVars.activeUserId;
                    item.Note = values[i, 3].ToString();

                    list.Add(item);
                }

                return list;
            }
            catch (System.Exception ex)
            {
                GlobalVars.ShowError(ex.Message);
                return null;
            }
        }

        private void lkSample_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            Process.Start("IExplore", System.Windows.Forms.Application.StartupPath + "\\Libs\\ClaimCouponsSample.xls");
        }

    }
}
